//
// Created by XUAN on 2024/8/26.
//

#include "button_control.h"
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "button_control.h"

#include <audio_tone_uri.h>
#include <audio_wrapper.h>
#include <board.h>
#include <ctype.h>
#include <i2s_stream.h>
#include <my_led_strip.h>
#include <nvs_operation.h>

#include "circuit_board.h"
#include "app.h"

/*---------------------------main parameters------------------------------*/
extern int msgId;          // 消息ID
extern int current_volume; // 当前音量
extern audio_board_handle_t board_handle;
extern char BT_MAC[35];
/*------------------------------------------------------------------*/

/*---------------------------audio_player------------------------------*/
extern EventGroupHandle_t play_event_group;
/*------------------------------------------------------------------*/


/*----------------------blufi_app-------------------------*/
extern bool wifi_connected;
extern bool gl_sta_connected;
extern bool gl_sta_got_ip;
/*--------------------------------------------------------*/

/*---------------------------audio_wrapper------------------------------*/
extern  bool voice_reading;
extern QueueHandle_t          rec_q ;
/*------------------------------------------------------------------*/

/*+++++++++++++++++++++++++++++++LED+++++++++++++++++++++++++++++++*/
extern int led_state;
extern uint8_t led_strip_pixels[STRIP_LED_NUMBER * 3];

extern int R_COLOR;
extern int G_COLOR;
extern int B_COLOR;
/*-------------------------------LED-------------------------------*/

/*+++++++++++++++++++++++++++++++APP+++++++++++++++++++++++++++++++*/
extern uint32_t last_action_time;
bool is_recording = false;
/*-------------------------------APP-------------------------------*/

bool button_recorder = false;

extern gpio_num_t BUTTON_FUNCTION;
extern gpio_num_t BUTTON_MODE;

static const char *TAG = "BUTTON_CONTROL";

static button_mode_t current_mode = MODE_CONVERSATION;  // 默认对话模式

// 播放不同模式的提示音
static void play_mode_tone(button_mode_t mode) {
    switch (mode) {
        case MODE_CONVERSATION:
            play_tone(HTT_MODE);  // 需要确保定义了 DIALOGUE_MODE_TONE
            ESP_LOGI(TAG, "Switched to conversation mode.");
        break;
        case MODE_VOLUME_ADJUST:
            play_tone(VA_MODE);    // 需要确保定义了 VOLUME_MODE_TONE
            ESP_LOGI(TAG, "Switched to volume adjust mode.");
        break;
        case MODE_RESET_NETWORK:
            play_tone(LPR_MODE);     // 需要确保定义了 RESET_MODE_TONE
            ESP_LOGI(TAG, "Switched to reset network mode.");
        break;
        default:
            break;
    }
}

void urlencode(const char *src, char *dest, size_t dest_size) {
    char *pDest = dest;
    const char *hex = "0123456789ABCDEF";
    while (*src && (pDest - dest < dest_size - 1)) {
        if (isalnum((unsigned char)*src) || *src == '-' || *src == '_' || *src == '.' || *src == '~') {
            *pDest++ = *src;
        } else {
            if (pDest - dest < dest_size - 3) {  // Ensure space for %XX
                *pDest++ = '%';
                *pDest++ = hex[(*src >> 4) & 0xF];
                *pDest++ = hex[*src & 0xF];
            }
        }
        src++;
    }
    *pDest = '\0';
}
char encoded_text[512]; // 保存编码后的URL文本
char url[1024];

void button_task(void *arg)
{
    // 配置 GPIO_NUM_0 作为输入
    gpio_config_t io_conf;
    io_conf.intr_type = GPIO_INTR_NEGEDGE;  // 下降沿触发中断
    io_conf.mode = GPIO_MODE_INPUT;
    io_conf.pin_bit_mask = (1ULL << BUTTON_FUNCTION) | (1ULL << BUTTON_MODE);
    io_conf.pull_up_en = GPIO_PULLUP_ENABLE;  // 上拉
    io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
    gpio_config(&io_conf);

    while (1) {
        if(!gl_sta_got_ip) {
            if (gpio_get_level(BUTTON_FUNCTION) == 0) {
                circuit_board_refresh_CountDown();
                while (gpio_get_level(BUTTON_FUNCTION) == 0) {
                    vTaskDelay(10 / portTICK_PERIOD_MS);  // 防抖延迟
                }
                play_tone(WIFI_CONFIG);
            }
            if(gpio_get_level(BUTTON_MODE) == 0) {
                circuit_board_refresh_CountDown();
                ESP_LOGI(TAG,"The network connection failed. Press and hold to reset the network configuration.");
                // 等待按钮松开
                while (gpio_get_level(BUTTON_MODE) == 0) {
                    vTaskDelay(10 / portTICK_PERIOD_MS);  // 防抖延迟
                }
                play_tone(WIFI_CONFIG);
            }
            vTaskDelay(100 / portTICK_PERIOD_MS);  // 主循环防抖延迟
            continue;
        }

        // 按下BUTTON_MODE按键，切换模式
        if (gpio_get_level(BUTTON_MODE) == 0) {
            led_state = LED_OFF;
            circuit_board_refresh_CountDown();
            msgId++;
            // 如果正在播放音频，则停止播放
            if (chat_audio_player_is_playing()) {
                ESP_LOGI(TAG, "Audio is playing, stopping playback...");
                chat_audio_stop_NOW();
                while (gpio_get_level(BUTTON_MODE) == 0) {
                    vTaskDelay(10 / portTICK_PERIOD_MS);  // 防抖延迟
                }
            } else {
                // 如果没有音频在播放，则切换模式
                ESP_LOGI(TAG, "No audio playing, switching mode...");
                // 等待按钮松开
                while (gpio_get_level(BUTTON_MODE) == 0) {
                    vTaskDelay(10 / portTICK_PERIOD_MS);  // 防抖延迟
                }
                // 切换模式
                current_mode = (current_mode + 1) % 3;  // 模式在 0, 1, 2 之间切换
                play_mode_tone(current_mode);  // 播放切换到的模式提示音
            }
        }

       // 根据当前模式执行不同操作
        switch (current_mode) {
            case MODE_CONVERSATION:  // 按住对话模式
             if (gpio_get_level(BUTTON_FUNCTION) == 0) {
                    circuit_board_refresh_CountDown();
                    ESP_LOGI(TAG, "Button pressed, starting conversation (recording)...");
                    led_state = LED_ON;
                    msgId++;  // 消息ID自增
                    chat_audio_stop_NOW();
                    chat_wwe_stop();
                    chat_stop_listen_handler();
                    vTaskDelay(100);
                    button_recorder = true;
                    if (voice_reading) {
                        int msg = REC_CANCEL;
                        if (xQueueSend(rec_q, &msg, 0) != pdPASS) {
                            ESP_LOGE(TAG, "rec cancel send failed");
                        }
                    }
                    voice_reading = false;
                    chat_listen_handler();
                    if (!voice_reading) {
                        int msg = REC_START;
                        if (xQueueSend(rec_q, &msg, 0) != pdPASS) {
                            ESP_LOGE(TAG, "rec start send failed");
                        }
                        ESP_LOGE(TAG,"BUTTON RECV START");
                    }
                    // 等待按钮松开
                    while (gpio_get_level(BUTTON_FUNCTION) == 0) {
                        vTaskDelay(10 / portTICK_PERIOD_MS);  // 防抖延迟
                    }
                    led_state = LED_RUNNING;
                    ESP_LOGI(TAG, "Button released, stopping conversation (recording)...");
                    chat_stop_listen_handler();
                    //打印voice_reading的状态
                    ESP_LOGI(TAG, "voice_reading: %d", voice_reading);
                    if (voice_reading) {
                        int msg = REC_STOP;
                        if (xQueueSend(rec_q, &msg, 0) != pdPASS) {
                            ESP_LOGE(TAG, "rec stop send failed");
                        }
                        ESP_LOGE(TAG,"BUTTON RECV STOP");
                    }
                    chat_wwe_start();
                    vTaskDelay(500);
                    button_recorder = false;
                    // play_tone(PING);
                }
            break;

            case MODE_VOLUME_ADJUST:  // 音量调节模式
                if (gpio_get_level(BUTTON_FUNCTION) == 0) {
                    circuit_board_refresh_CountDown();
                    ESP_LOGI(TAG, "Button pressed, adjusting volume...");
                    // 在这里添加音量调节逻辑（例如增大/减小音量）
                    // 每次增加20
                    current_volume += 20;
                    // 如果增加后的音量超过100，则将音量重置为20
                    if (current_volume > 100) {
                        current_volume = 20;
                    }
                    // 设置新的音量
                    chat_volume_set_handler(current_volume);

#ifdef RMT_FUNCTION
                    for (int i = 0; i < STRIP_LED_NUMBER * current_volume / 100; i++)
                    {
                        led_strip_pixels[i * 3 + 0] = G_COLOR;
                        led_strip_pixels[i * 3 + 1] = B_COLOR;
                        led_strip_pixels[i * 3 + 2] = R_COLOR;
                    }
                    for (int i = STRIP_LED_NUMBER * current_volume / 100; i < STRIP_LED_NUMBER; i++)
                    {
                        led_strip_pixels[i * 3 + 0] = 0;
                        led_strip_pixels[i * 3 + 1] = 0;
                        led_strip_pixels[i * 3 + 2] = 0;
                    }
                    led_refresh();
#endif

                    play_tone(VOL_CHANGE);

                    ESP_LOGI(TAG, "Volume set to: %d", current_volume);
                    // 等待按钮松开
                    while (gpio_get_level(BUTTON_FUNCTION) == 0) {
                        vTaskDelay(10 / portTICK_PERIOD_MS);  // 防抖延迟
                    }
                    ESP_LOGI(TAG, "Button released, volume adjusted.");
                }
            break;

            case MODE_RESET_NETWORK:  // 长按重置网络模式
                int hold_cnt_time = 0;
                bool restTAG = false;
                if (gpio_get_level(BUTTON_FUNCTION) == 0) {
                    circuit_board_refresh_CountDown();
                    ESP_LOGI(TAG, "Button pressed, resetting network...");
                    while (gpio_get_level(BUTTON_FUNCTION) == 0) {
                        vTaskDelay(200);
                        hold_cnt_time++;
                        if(hold_cnt_time > 20) {
                            if (reset_wifi_list()) {
                                restTAG = true;
                                ESP_LOGI(TAG, "WiFi list reset successfully");
                            } else {
                                ESP_LOGE(TAG, "Failed to reset WiFi list");
                            }
                            if(restTAG) {
                                play_sync_tone(RESTART);
                            }
                            break;
                        }
                        vTaskDelay(10 / portTICK_PERIOD_MS);  // 防抖延迟
                    }
                    if (restTAG) {
                        esp_restart();
                    }

                    ESP_LOGI(TAG, "Button released, network reset.");
                }
            break;

            default:
                break;
        }
        vTaskDelay(10 / portTICK_PERIOD_MS);  // 主循环防抖延迟
    }
}

void button_control_init(void)
{
    esp_log_level_set("*", ESP_LOG_INFO);
    xTaskCreate(button_task, "button_task", 1024 * 4, NULL, 10, NULL);
}

